const StudentModel = require("../model/StudentModel")

const StudentService = {
    getList:async () => {
        //联系role集合查询
        return await StudentModel.find().populate("class")
    },
    addList:async (body) => {
        const list = body.list.map(item => ({
            studentname:item.studentname,
            class:body.class,
            score:{},
            password:'123'
        }))
        for(let i of list){
            await StudentModel.updateOne({
                studentname:i.studentname
            },{
                $set:i
            },{
                upsert:true
            })
        }
        return []
    },
    login:async (data)=>{
        return await StudentModel.find(data)
    },
    deleteList:async(id) => {
        //删除所有包含classid的数据
        return await StudentModel.deleteMany({class:id})
    },
    updateList:async(id,{key,value}) => {
        return await StudentModel.findByIdAndUpdate(id,{
            "$set":{
                ["score."+key]:value
            }
        })
    },
    upload:async (id,file,body) => {
        if(file){
            return await StudentModel.findByIdAndUpdate(id,{
                ...body,
                studentname:body.username,
                avatarUrl:`/uploads/${file.filename}`
            },{returnDocument:"after"/*返回更新后的文档*/})
        }else{
            return await StudentModel.findByIdAndUpdate(id,{
                ...body,
                studentname:body.username,
                // avatarUrl:`/uploads/${file.filename}`
            },{returnDocument:"after"/*返回更新后的文档*/})
        }
    }
}
module.exports = StudentService